package com.thfw.test.view.activity;


import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.input.InputManager;
import android.inputmethodservice.InputMethodService;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.thfw.test.MyApplication;
import com.thfw.test.view.mq.PahoHepler;
import com.thfw.wmd.R;
import com.thfw.test.model.authManage.AuthBaseBean;
import com.thfw.test.model.authManage.PriceBean;
import com.thfw.test.model.authManage.TokenBean;
import com.thfw.test.model.bean.CaptchaBean;
import com.thfw.test.model.bean.PriceBeanBean;
import com.thfw.test.utils.BluetoothDeviceManager;
import com.thfw.test.utils.ConfigurationEntry;
import com.thfw.test.utils.HexUtil;
import com.thfw.test.utils.StringUtils;
import com.thfw.test.utils.ToastUtils;
import com.thfw.test.utils.WifiAutoConnectManager;
import com.thfw.test.utils.WifiUtils;
import com.thfw.test.view.ViseBle;
import com.thfw.test.view.adapter.WifiListAdapter;
import com.thfw.test.view.common.PropertyType;
import com.thfw.test.view.core.DeviceMirror;
import com.thfw.test.view.event.CallbackDataEvent;
import com.thfw.test.view.event.NotifyDataEvent;
import com.thfw.test.view.model.BluetoothLeDevice;
import com.thfw.test.view.model.resolver.GattAttributeResolver;
import com.thfw.test.view.network.AuthManageService;
import com.vise.xsnow.cache.SpCache;
import com.vise.xsnow.event.Subscribe;


import org.json.JSONObject;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import scooper.cn.sc_base.AppActivities;
import scooper.cn.sc_base.log.SCLog;
import utils.PasswordUtils;
import utils.RetrofitWrapper;

import static com.thfw.test.utils.WifiAutoConnectManager.WifiCipherType.WIFICIPHER_NOPASS;
import static com.vise.utils.view.InputMethodUtil.hideSoftInput;

public class LoginActivity extends BaseActivity {

    private static final String TAG = LoginActivity.class.getCanonicalName();
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    ArrayList<ScanResult> list;
    LayoutInflater inflater;
    View layout;
    ListView myListView;
    ImageButton myImageButtion;
    Timer timer;
    TimerTask timerTask;
    String uuid;
    @BindView(R.id.rl_background)
    RelativeLayout rl_background;
    @BindView(R.id.ll_background)
    LinearLayout ll_background;
    @BindView(R.id.ok)
    Button ok;
    @BindView(R.id.ed_username)
    EditText ed_username;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.settingDialog)
    LinearLayout settingDialog;
    @BindView(R.id.login_setting)
    TextView login_setting;
    TextView tv_label;
    @BindView(R.id.cancel_btn)
    TextView cancelBtn;
    @BindView(R.id.ok_btn)
    TextView okBtn;
    @BindView(R.id.et_out_host)
    EditText outHost;
    @BindView(R.id.et_out_port)
    EditText outPort;
    @BindView(R.id.iv_base64)
    ImageView iv_base64;
    @BindView(R.id.et_base64)
    EditText et_base64;
    @BindView(R.id.cb_rem_password)
    CheckBox cb_rem_password;

    final Handler handler = new Handler(msg -> {
        switch (msg.what) {
            case 1:
                break;
            default:
                break;
        }
        return false;
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_wifilogin_new;
    }


    @Override
    protected void onResume() {
        super.onResume();
        et_base64.setText("");
        getCaptcha(iv_base64, outHost.getText().toString(), Integer.valueOf(outPort.getText().toString()));
    }

    @Override
    public void initView() {
        inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.formcommonlist, null);
        myListView = layout.findViewById(R.id.formcustomspinner_list);
        myImageButtion = layout.findViewById(R.id.btn_reload);
        tv_label = layout.findViewById(R.id.tv_label);
        ed_username.setText(getConfig().getString(ConfigurationEntry.USERNAME, "super"));
        password.setText(getConfig().getString(ConfigurationEntry.PASSWORD, "super"));
        outHost.setText(getConfig().getString(ConfigurationEntry.HOST, "192.168.103.174"));
        outPort.setText(getConfig().getInt(ConfigurationEntry.PORT, 8090) + "");
        cb_rem_password.setChecked(getConfig().getBoolean(ConfigurationEntry.REMEMBERPASSWORD, false));
        if (cb_rem_password.isChecked()) {
            password.setText(getConfig().getString(ConfigurationEntry.PASSWORD, "super"));
        } else {
            password.setText("");
        }
        final TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(500);

        final TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f);
        mHiddenAction.setDuration(500);


        ok.setOnClickListener(v -> {


//            AppActivities.instance().finishTo(LoginActivity.this, ControlActivity2.class);

            if (et_base64.getText().toString().equals("") || et_base64.getText().toString() == null) {
                Toast.makeText(LoginActivity.this, "验证码为空，请检查", Toast.LENGTH_SHORT).show();
                return;
            } else if (ed_username.getText().toString().equals("") || ed_username.getText().toString().equals("")) {
                Toast.makeText(LoginActivity.this, "用户名为空，请检查", Toast.LENGTH_SHORT).show();
                return;
            } else if (password.getText().toString().equals("") || password.getText().toString().equals("")) {
                Toast.makeText(LoginActivity.this, "密码为空，请检查", Toast.LENGTH_SHORT).show();
                return;
            }
            connectService(ed_username.getText().toString()
                    , password.getText().toString()
                    , outHost.getText().toString()
                    , Integer.valueOf(outPort.getText().toString())
                    , uuid, et_base64.getText().toString());

        });


        rl_background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftInput(v);
            }
        });
        cb_rem_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    getConfig().putBoolean(ConfigurationEntry.REMEMBERPASSWORD, true, true);
                } else {
                    getConfig().putBoolean(ConfigurationEntry.REMEMBERPASSWORD, false, true);
                }
            }
        });
        iv_base64.setOnClickListener(v -> {
            getCaptcha(iv_base64, outHost.getText().toString(), Integer.valueOf(outPort.getText().toString()));
            et_base64.setText("");
        });
        login_setting.setOnClickListener(view -> {
            settingDialog.startAnimation(mShowAction);
            settingDialog.setVisibility(View.VISIBLE);
            ll_background.setVisibility(View.INVISIBLE);
            hideSoftInput(view);
        });

        cancelBtn.setOnClickListener(view -> {
            settingDialog.startAnimation(mHiddenAction);
            settingDialog.setVisibility(View.GONE);
            ll_background.setVisibility(View.VISIBLE);
        });
        okBtn.setOnClickListener(view -> {
            if (!isIp(outHost.getText().toString()) && outHost.getText().toString().length() > 0) {
                Toast.makeText(LoginActivity.this, "请输入正确的外网IP！", Toast.LENGTH_SHORT).show();
                return;
            } else if (!isPort(outPort.getText().toString()) && outPort.getText().toString().length() > 0) {
                Toast.makeText(LoginActivity.this, "外网端口格式错误！", Toast.LENGTH_SHORT).show();
                return;
            } else {
                settingDialog.startAnimation(mHiddenAction);
                settingDialog.setVisibility(View.GONE);
                ll_background.setVisibility(View.VISIBLE);
                getConfig().putString(ConfigurationEntry.HOST, outHost.getText().toString());
                getConfig().putInt(ConfigurationEntry.PORT, Integer.valueOf(outPort.getText().toString()));
                getConfig().commit();
                //
            }
        });


        builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        alertDialog = builder.create();

        //请求验证码
//        getCaptcha(iv_base64, outHost.getText().toString(), Integer.valueOf(outPort.getText().toString()));

    }


    public void showDialog() {
        alertDialog.show();
        startTimerTask();
    }


    void startTimerTask() {
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(1);
                }
            };

        }
        timer.schedule(timerTask, 1000, 3 * 1000);
    }

    void resetTask() {
        if (timer != null) {
            timer.cancel();
        }
        if (timerTask != null) {
            timerTask.cancel();
        }
        timerTask = null;
        timer = null;
    }

    @Override
    protected void onPause() {
        super.onPause();
        resetTask();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetTask();
    }


    private boolean isPort(String port) {
        if (!TextUtils.isEmpty(port)
                && !(Long.parseLong(port) > 0
                && Long.parseLong(port) <= 65535)) {
            return false;
        }
        return true;
    }


    public boolean isIp(String ipAddress) {
        String ipRegex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])" +
                "(\\.(\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])){3}$";
        Pattern pattern = Pattern.compile(ipRegex);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches() || isDomainName(ipAddress);
    }


    public static boolean isDomainName(String domain) {
        if (domain.length() < 3 || domain.length() > 67) {
            return false;
        }
        String[] arr = domain.split("\\.");
        if (arr.length < 2) {
            return false;
        }
        String regex2c = "^[a-zA-Z0-9]{1,2}$";
        String regex = "^[a-zA-Z0-9][a-zA-Z0-9\\-]+[a-zA-Z0-9]$";
        Pattern pattern2c = Pattern.compile(regex2c);
        Pattern pattern = Pattern.compile(regex);
        for (String value : arr) {
            if (value.length() <= 2) {
                Matcher matcher = pattern2c.matcher(value);
                if (!matcher.matches()) {
                    return false;
                }
            } else {
                Matcher matcher = pattern.matcher(value);
                if (!matcher.matches()) {
                    return false;
                }
            }
        }
        return true;
    }

    private void getCaptcha(ImageView iv_base64, final String host, final int port) {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();

            Map<String, String> params = new HashMap<String, String>();


            RetrofitWrapper.getInstance(this, true, url).create(AuthManageService.class).getCaptcha(params).enqueue(new Callback<AuthBaseBean<CaptchaBean>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<CaptchaBean>> call, Response<AuthBaseBean<CaptchaBean>> response) {
                    SCLog.e(TAG, "response is ok" + response.message());
                    if (response != null && response.body() != null && response.body().getData() != null) {
                        CaptchaBean captchaBean = response.body().getData();
                        if (captchaBean.getUuid() != null) {
                            uuid = captchaBean.getUuid();
                            setBase64Image(iv_base64, captchaBean.getImg());
                        }
                    }

                }

                @Override
                public void onFailure(Call<AuthBaseBean<CaptchaBean>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());
                    iv_base64.setImageResource(R.mipmap.icon_load_error);
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    private void connectService(final String user, final String pass, final String host, final int port, String uuid, String code) {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();

            Map<String, String> params = new HashMap<>();
            params.put("username", user);
            params.put("password", PasswordUtils.sha(pass));
            params.put("code", code);
            params.put("uuid", uuid);

            RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json;"),
                    new JSONObject(params).toString());

            RetrofitWrapper.getInstance(this, true, url).create(AuthManageService.class).getToken(requestBody).enqueue(new Callback<TokenBean>() {
                @Override
                public void onResponse(Call<TokenBean> call, Response<TokenBean> response) {
                    if (response != null && response.body() != null) {
                        TokenBean tokenBean = response.body();
                        if (tokenBean != null && tokenBean.getCode() == 200) {
                            getConfig().putString(ConfigurationEntry.TOKEN, tokenBean.getToken(), true);
                            AppActivities.instance().finishTo(LoginActivity.this, ControlActivity2.class);
                            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                            getConfig().putString(ConfigurationEntry.PASSWORD, password.getText().toString(), true);
                            getConfig().putString(ConfigurationEntry.USERNAME, ed_username.getText().toString(), true);
                            if (tokenBean.getNickname() != null) {
                                getConfig().putString(ConfigurationEntry.NAME, tokenBean.getNickname(), true);
                            }
                            PahoHepler.getInstance().initConfig((MyApplication) getApplicationContext(),host,String.valueOf(1883),"test");
                            PahoHepler.getInstance().connect();


                        } else {
                            Toast.makeText(LoginActivity.this, tokenBean.getMsg(), Toast.LENGTH_LONG).show();
                            et_base64.setText("");
                            getCaptcha(iv_base64, outHost.getText().toString(), Integer.valueOf(outPort.getText().toString()));
                        }
                    }else{
                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                    }
                }
            @Override
            public void onFailure (Call < TokenBean > call, Throwable t){
                et_base64.setText("");
                getCaptcha(iv_base64, outHost.getText().toString(), Integer.valueOf(outPort.getText().toString()));
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
            }
        });
    } catch(
    MalformedURLException e)

    {
        e.printStackTrace();
    }

}





    public void setBase64Image(ImageView ivCode, String imgUrl) {
        byte[] decode = Base64.decode(imgUrl.split(",")[1], Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        ivCode.setImageBitmap(bitmap);
    }

}
